package com.liu.controller;

import com.liu.domain.dm;
import com.liu.repository.DmRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by liu on 17-9-21.
 */
@RestController
public class DmController {
    private final static Logger logger = LoggerFactory.getLogger(DmController.class);

    @Autowired
    private DmRepository dmRepository;

    /*
    查询所有宿管列表
     */
    @GetMapping(value = "/dm")
    public String dmList(){
        System.out.println("dmList");

        logger.info("dmList");

        //return dmRepository.findAll();
        return "{\"code\":0,\"msg\":\"\",\"count\":1000,\"data\":" + dmRepository.findAll() + "}";

    }

    //通过session
    @GetMapping(value = "/dm/sess")
    @ResponseBody
    public dm sessionById(String dm_id ,HttpSession session) {

        dm dm = (com.liu.domain.dm) session.getAttribute("user");
        int id = dm.getDm_id();
        System.out.print(dm);
        return dmRepository.findById(id);
    }
    /*
    添加一名宿管
     */
    @PostMapping(value = "/dm")
    public dm dmAdd(dm dm) {


        return dmRepository.save(dm);
    }

    /*
    更新一个宿管的信息
     */
    @PutMapping(value = "/dm/{dm_id}")
    public dm dmUpdate(@PathVariable("dm_id") Integer dm_id, dm dm) {

        return dmRepository.save(dm);
    }
    /*
    删除一个宿管
     */

    @DeleteMapping(value = "/dm/{dm_id}")
    public void dmDelete(@PathVariable("dm_id") Integer dm_id){
        dmRepository.delete(dm_id);
    }


    //通过id查询
    @GetMapping(value = "/dm/id/{dm_id}")
    public dm dmById(@PathVariable("dm_id") Integer dm_id) {
        return dmRepository.findById(dm_id);
    }


    //通过姓名查询
    @GetMapping(value = "/dm/name/{name}")
    public List<dm> dmByName(@PathVariable("name") String name) {
        return dmRepository.findByName(name);
    }

    //通过楼栋查询
    @GetMapping(value = "/dm/build/{build_id}")
    public List<dm> dmByBuild(@PathVariable("build_id") Integer build_id) {
        return dmRepository.findByBuild(build_id);}

    @PostMapping("/checkfomXt")
    public String checkForm(String oldPwd, String newPwd, String reNewPwd, HttpSession session) {
        dm dm = (com.liu.domain.dm) session.getAttribute("user");
        if (!dm.getPassword().equals(oldPwd)) {
            return "原密码错误";
        }
        if (!reNewPwd.equals(newPwd)) {
            return "两次输入密码不一致";
        }
        dm.setPassword(newPwd);
        dmRepository.save(dm);
        return "修改成功";
    }

}
